package main

import (
	"fmt"
	"log"
	"math/rand"
	"module-10/metrics"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/prometheus/client_golang/prometheus/promhttp"
)

//index方法
func index(w http.ResponseWriter, r *http.Request) {
	//遍历http header 的信息
	for k, v := range r.Header {
		for _, vv := range v {
			fmt.Printf("Header key: %s, Header value: %s \n", k, v)
			//将header加入到response header中
			w.Header().Set(k, vv)
		}
	}
	_, _ = w.Write([]byte("请求成功，请在终端查看！"))
	//获取系统的VERSION环境变量的值，并加入到到response header中
	version := os.Getenv("VERSION")
	w.Header().Set("VERSION", version)
}

//获取客户端ip
func ReadUserIP(r *http.Request) string {
	IPAddress := r.Header.Get("X-Real-Ip")
	if IPAddress == "" {
		IPAddress = r.Header.Get("X-Forwarded-For")
	}
	if IPAddress == "" {
		IPAddress = strings.Split(r.RemoteAddr, ":")[0]
	}
	return IPAddress
}

//获取返回码
func healthz(w http.ResponseWriter, r *http.Request) {
	_, _ = w.Write([]byte("200"))
}

//增加延时
func images(w http.ResponseWriter, r *http.Request) {
	timer := metrics.NewTimer()
	defer timer.ObserveTotal()
	randInt := rand.Intn(2000)
	time.Sleep(time.Millisecond * time.Duration(randInt))
	w.Write([]byte(fmt.Sprintf("<h1>%d<h1>", randInt)))
}
func main() {
	metrics.Register()
	//创建一个http服务
	serverMux := http.NewServeMux()
	//匹配/，定义一个index方法
	serverMux.HandleFunc("/", index)
	//匹配/healthz，定义一个healthz方法
	serverMux.HandleFunc("/healthz", healthz)
	serverMux.HandleFunc("/images", images)		
	serverMux.Handle("/metrics", promhttp.Handler())
	//设置监听地址
	err := http.ListenAndServe(":80", serverMux)
	log.Fatal(err)
}
